package com.mrzhou.auth.serialize;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.mrzhou.auth.exception.IntegrationOAuth2Exception;
import com.mrzhou.core.tool.constants.ApplicationConstant;
import com.mrzhou.web.util.WebUtil;

import java.io.IOException;
import java.util.Map;

/**
 * IntegrationOAuth2Exception.class序列化器
 */
public class IntegrationOAuth2ExceptionSerializer extends StdSerializer<IntegrationOAuth2Exception> {

    protected IntegrationOAuth2ExceptionSerializer() {
        super(IntegrationOAuth2Exception.class);
    }

    @Override
    public void serialize(IntegrationOAuth2Exception value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeNumberField(ApplicationConstant.R_CODE, value.getHttpErrorCode());
        gen.writeBooleanField(ApplicationConstant.R_SUCCESS, false);
        gen.writeObjectField(ApplicationConstant.R_MSG, hanlderMessage(value));
        gen.writeObjectField(ApplicationConstant.R_DATA, null);
        if (value.getAdditionalInformation()!=null) {
            for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String add = entry.getValue();
                gen.writeStringField(key, add);
            }
        }
        gen.writeEndObject();
    }

    /**
     * 处理spring
     * @return
     */
    private String hanlderMessage(IntegrationOAuth2Exception value) {
        String grantType = WebUtil.getParameter("grant_type");
        String message = value.getMessage();
        String errorCode = value.getOAuth2ErrorCode();
        if(errorCode.equals("invalid_request") && message.indexOf("grant type") != -1) {
            return String.format("当前的Authorization不支持%s的登录方式", grantType);
        }
        return message;
    }

}
